﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.Unity;
using ePlanet.ArchiveMange.Services;
using Web.SystemConfig.Services;
using Web.SystemConfig.WorkFlow;
using ePlanet.ArchiveMange.Models;
using System.Data;
using Wuqi.Webdiyer;
using CommonModule;
using ePlanet.Entities;

namespace Web.Views.DataManage
{
    public partial class OilSearchZongheVol : PageBase
    {
        #region  页面属性
        /// <summary>
        /// 档案编目接口
        /// </summary>
        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }

        /// <summary>
        /// 勘探综合卷接口
        /// </summary>
        [Dependency]
        public IZongheVolService ZongheVol
        {
            get;
            set;
        }

        /// <summary>
        /// 码表接口
        /// </summary>
        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }

        /// <summary>
        /// 文档类型ID
        /// </summary>
        public int ArchiveTypeID
        {
            get
            {
                int o_int = 1;
                if (Request.QueryString["archivetype"] != null)
                {
                    if (int.TryParse(Request.QueryString["archivetype"], out o_int))
                    {
                        return o_int;
                    }
                    else
                    {
                        return (int)ArchiveTableEnum.OliSearch_Zonghe_Vol;
                    }
                }
                else
                {
                    return (int)ArchiveTableEnum.OliSearch_Zonghe_Vol;
                }

            }
        }

        private string archiveTypeName = string.Empty;
        public string ArchiveTypeName
        {
            get
            {
                if (!string.IsNullOrEmpty(archiveTypeName))
                {
                    return this.archiveTypeName;
                }
                else
                {
                    if (ArchiveTypeID == (int)ArchiveTableEnum.OliSearch_Zonghe_Vol)
                    {
                        archiveTypeName = "勘探(综合)卷";
                    }
                    return this.archiveTypeName;
                }
            }
        }

        private string UserSessionTempDirectoryId
        {
            get
            {
                return this.Session.SessionID;
            }
        }
        #endregion

        #region 页面初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            this.sch.SearchEvent += new EventHandler(sch_SearchEvent);
            if (!IsPostBack)
            {
                BindArchiveGrid(string.Empty);
                string webAddress = "http://" + this.Request.Url.Authority + this.Request.ApplicationPath;
                webAddress = HttpUtility.UrlEncode(webAddress);
                this.ImportData.NavigateUrl = "~/FilesUploadClickOnce/FilesUpload.application?UserId=" + this.CurrentUser.User_ID + "&WebAddress=" + webAddress + "&CatalogId=7101&Type=Archive";
            }
        }

        /// <summary>
        /// 绑定列表
        /// </summary>
        private void BindArchiveGrid(string filter)
        {
            //绑定Grid
            DataTable archiveTable = ZongheVol.GetAllDocumenArchivetByFilter(filter);
            //对全宗号进行过滤
            DataRow[] rows = archiveTable.Select("fullfondsnum='" + this.CurrentUser.Org_FullFondsNum + "'");
            DataTable archive = archiveTable.Clone();
            foreach (DataRow row in rows)
            {
                archive.ImportRow(row);
            }
            this.FileSearch.RecordCount = archive.Rows.Count;
            int pageindex = this.FileSearch.CurrentPageIndex;
            int pagesize = this.FileSearch.PageSize;
            DataTable dt = PageDataList.GetPagedTable(archive, pageindex, pagesize);
            ConvertCodeTableInfo.ReplaceKeyToValueInDataTable(dt);
            this.gv_ArchiveFileList.DataSource = dt;
            this.gv_ArchiveFileList.DataBind();
            //初始化导出过滤条件
            InitCheckBoxList(dt);
        }
        #endregion

        #region  页面方法
        /// <summary>
        /// 初始化导出列
        /// </summary>
        /// <param name="oDataTable"></param>
        private void InitCheckBoxList(DataTable oDataTable)
        {
            if (oDataTable != null)
            {
                List<ColumnNameToCHS> columnNameToCHSList = ColumnNameToCHS.GetColumnNameToCHSLisToHistoryArhive();
                DataTable dt = new DataTable();
                dt.Columns.Add("ColName", typeof(string));
                dt.Columns.Add("CHSName", typeof(string));
                DataRow row = null;
                foreach (DataColumn col in oDataTable.Columns)
                {
                    foreach (ColumnNameToCHS item in columnNameToCHSList)
                    {
                        if (col.ColumnName.ToLower() == item.ColumnName.ToLower())
                        {
                            row = dt.NewRow();
                            row["ColName"] = item.ColumnName;
                            row["CHSName"] = item.CHSName;
                            dt.Rows.Add(row);
                            break;
                        }
                    }
                }
                this.cblSelectCols.DataTextField = "CHSName";
                this.cblSelectCols.DataValueField = "ColName";
                this.cblSelectCols.DataSource = dt;
                this.cblSelectCols.DataBind();
                foreach (System.Web.UI.WebControls.ListItem ck in this.cblSelectCols.Items)
                {
                    ck.Selected = true;
                }
            }
        }


        /// <summary>
        /// 获取所有页选择的行
        /// </summary>
        public void SetSelectItemsInAllPages()
        {
            if (this.ViewState["SelectItemsInAllPages"] == null)
            {
                this.ViewState["SelectItemsInAllPages"] = new System.Collections.ArrayList();
            }
            System.Collections.ArrayList selectItemsInAllPages = this.ViewState["SelectItemsInAllPages"] as System.Collections.ArrayList;
            if (this.gv_ArchiveFileList.ShowCheckBox)
            {
                for (int i = 0; i < this.gv_ArchiveFileList.Rows.Count; i++)
                {
                    //主键ID[如果没有配置主键，会抛出异常]
                    string id = this.gv_ArchiveFileList.DataKeys[i].Value.ToString();
                    foreach (TableCell tc in this.gv_ArchiveFileList.Rows[i].Cells)
                    {
                        if (tc.Controls.Count > 0 && tc.Controls[0] is System.Web.UI.WebControls.CheckBox)
                        {
                            System.Web.UI.WebControls.CheckBox cb = tc.Controls[0] as System.Web.UI.WebControls.CheckBox;
                            if (cb.Checked)
                            {
                                if (!selectItemsInAllPages.Contains(id))
                                {
                                    selectItemsInAllPages.Add(id);
                                }
                            }
                            else
                            {
                                if (selectItemsInAllPages.Contains(id))
                                {
                                    selectItemsInAllPages.Remove(id);
                                }
                            }
                        }
                    }
                }
            }

            this.ViewState["SelectItemsInAllPages"] = selectItemsInAllPages;

            this.gv_ArchiveFileList.ResetSelectItemsInViewState(selectItemsInAllPages);
        }
        #endregion

        #region 页面事件
        /// <summary>
        /// Gridview绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gv_ArchiveFileList_OnDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e != null && e.Row != null && e.Row.RowType == DataControlRowType.DataRow)
            {
                string id = this.gv_ArchiveFileList.DataKeys[e.Row.RowIndex].Value.ToString();
                string elecFileCount = ArchiveBusiHelper.Instance.GetTechnologyFileCount(ArchiveMenuService.GetArchiveBaseIDById(ArchiveTypeID), id);
                if (!string.IsNullOrEmpty(elecFileCount))
                {
                    e.Row.Cells[1].Text = string.Format("<img src='{0}' alt='{1}个电子文件' />",
                        "../../Images/qbz.jpg", elecFileCount);
                }
                else
                {
                    e.Row.Cells[1].Text = string.Empty;
                }
            }
        }
        /// <summary>
        /// GridView删除执行后执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gv_ArchiveFileList_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
        }
        /// <summary>
        /// GridView删除执行前执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gv_ArchiveFileList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
        }

        /// <summary>
        /// 翻页控件翻页事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileSearch_PageChanging(object sender, PageChangingEventArgs e)
        {
            SetSelectItemsInAllPages();
            this.IsExportRowsOrColumnsEmpty.Value = "false";
            this.FileSearch.CurrentPageIndex = e.NewPageIndex;
            BindArchiveGrid(this.sch.WhereString);
        }

        /// <summary>
        /// 翻页控件改变页大小事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected void FileSearch_PageSizeChanging(object sender, EventArgs args)
        {
            this.ViewState["SelectItemsInAllPages"] = null;
            this.gv_ArchiveFileList.ResetSelectItemsInViewState(null);
            this.IsExportRowsOrColumnsEmpty.Value = "false";
            BindArchiveGrid(this.sch.WhereString);
        }
        #endregion

        #region 按钮事件

        protected void sch_SearchEvent(object sender, EventArgs e)
        {
            BindArchiveGrid(this.sch.WhereString);
        }

        /// <summary>
        /// 导出为Excel按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            DataTable t1 = ZongheVol.GetAllDocumenArchivetByFilter(this.sch.WhereString);
            DataTable archiveTable = new DataTable();
            foreach (DataColumn dc in t1.Columns)
            {
                DataColumn dcc = new DataColumn();
                dcc.ColumnName = dc.ColumnName;
                dcc.DataType = dc.DataType;
                archiveTable.Columns.Add(dcc);
            }
            foreach (DataRow row in t1.Rows)
            {
                archiveTable.Rows.Add(row.ItemArray);
            }
            ConvertCodeTableInfo.ReplaceKeyToValueInDataTable(archiveTable);
            string msg = string.Empty;
            bool breturn = true;
            System.Collections.ArrayList dataIds = null;
            //对数据源的列进行过滤
            if (this.IsExportAllRowsHasSelected.SelectedValue == "0")
            {
                this.gv_ArchiveFileList.ResetSelectItemsInViewState(null);
                dataIds = this.gv_ArchiveFileList.SelectItems;
                SetSelectItemsInAllPages();
            }
            else
            {
                SetSelectItemsInAllPages();
                dataIds = this.ViewState["SelectItemsInAllPages"] as System.Collections.ArrayList;
            }
            string wheres = string.Empty;
            if (archiveTable.Columns.Contains("DataId") && dataIds.Count > 0)
            {
                wheres = " 1=1 AND DataId IN ( ";
                foreach (string dataId in dataIds)
                {
                    wheres += "'" + dataId + "',";
                }
                wheres = wheres.Remove(wheres.Length - 1);
                wheres += " ) ";
            }
            else
            {
                wheres = "1=0";
            }
            DataRow[] rows = archiveTable.Select(wheres);
            DataTable dtArchive = archiveTable.Clone();
            foreach (DataRow row in rows)
            {
                dtArchive.Rows.Add(row.ItemArray);
            }
            dtArchive.AcceptChanges();
            //对未选中的列进行过滤
            List<string> selectColumnNames = new List<string>();
            foreach (ListItem item in this.cblSelectCols.Items)
            {
                if (item.Selected == true && archiveTable.Columns.Contains(item.Value))
                {
                    selectColumnNames.Add(item.Value);
                }
            }

            if (dataIds.Count == 0 || (selectColumnNames.Count == 0))
            {
                msg = "ColumnsOrRowsEmpty";
                breturn = false;
            }
            foreach (DataColumn col in archiveTable.Columns)
            {
                if (col.ColumnName.ToLower() != "dataid" && !selectColumnNames.Contains(col.ColumnName, StringComparer.OrdinalIgnoreCase))
                {
                    if (dtArchive.Columns.CanRemove(dtArchive.Columns[col.ColumnName]))
                    {
                        dtArchive.Columns.Remove(col.ColumnName);
                    }
                }
            }
            DataRow[] rows_ = dtArchive.Select(wheres);
            DataTable dtArchiveExportDataSource = dtArchive.Clone();
            foreach (DataRow row in rows_)
            {
                dtArchiveExportDataSource.Rows.Add(row.ItemArray);
            }
            if (dtArchiveExportDataSource.Columns.Contains("DataId"))
            {
                dtArchiveExportDataSource.Columns["DataId"].SetOrdinal(0);
            }
            dbDataTableAddXuHao(dtArchiveExportDataSource, "Xuhao");
            DataSet ds = new DataSet();
            //电子文件
            dtArchiveExportDataSource.Columns.Add("AttachmentCount");//存储电子文件数目
            dtArchiveExportDataSource.Columns.Add("AttachmentPath");//电子文件路径
            DataHelper dataHelper = new DataHelper();
            string dbHelperName = dataHelper.GetDbHelperNameByArchiveType(string.Concat(this.ArchiveTypeID));
            DataTable dtArchiveExportDataSourceCopy = dtArchiveExportDataSource.Clone();
            for (int i = 0; i < dtArchiveExportDataSource.Rows.Count; i++)
            {
                DataRow rowExport = dtArchiveExportDataSource.Rows[i];
                DataTable table = dataHelper.GetAttachmentIds(new List<string>() { rowExport["DataId"].ToString() }, dbHelperName);
                rowExport["AttachmentCount"] = table.Rows.Count;
                if (table.Rows.Count > 0)
                {
                    for (int j = 0; j < table.Rows.Count; j++)
                    {
                        DataRow rowAttach = table.Rows[j];
                        AttachmentInfo info = new AttachmentInfo { Id = string.Concat(rowAttach["ATTACHMENTID"]), Name = string.Concat(rowAttach["ATTACHMENTNAME"]), FileSize = int.Parse(string.Concat(rowAttach["ATTACHMENTSIZE"])), SaveDirectory = string.Concat(rowExport["ArchiveNum"]), DbHelperString = dbHelperName };
                        string infoJson = Newtonsoft.Json.JsonConvert.SerializeObject(info);
                        if (j == 0)
                        {
                            rowExport["AttachmentPath"] = infoJson;
                            dtArchiveExportDataSourceCopy.ImportRow(rowExport);
                        }
                        else
                        {
                            DataRow rowExportNewRow = dtArchiveExportDataSourceCopy.NewRow();
                            rowExportNewRow["AttachmentPath"] = infoJson;
                            dtArchiveExportDataSourceCopy.Rows.Add(rowExportNewRow);
                        }
                    }
                }
                else
                {
                    dtArchiveExportDataSourceCopy.ImportRow(rowExport);
                }
            }
            //卷信息存入dataset
            dtArchiveExportDataSourceCopy.TableName = "Table";
            ds.Tables.Add(dtArchiveExportDataSourceCopy);

            //保存到临时文件
            string templetePath = this.Server.MapPath(AsposeExprtToExcel.GetTempletePath(ArchiveTypeID));
            string excelImportName = this.ArchiveTypeName.Replace(" ", "") + "_" + string.Concat(Guid.NewGuid()) + ".xls";
            string userTempDirect = this.Request.PhysicalApplicationPath + "\\TempDatas\\" + UserSessionTempDirectoryId;
            if (!System.IO.Directory.Exists(userTempDirect))
            {
                System.IO.Directory.CreateDirectory(userTempDirect);
            }
            string excelImportTempPath = System.IO.Path.Combine(userTempDirect, excelImportName);
            //注释的代码做手动测试用，导出excel之后手动执行批量导出工具
            //AsposeExprtToExcel.ExportToExcel(ds, templetePath, ArchiveTypeName, this.Response);
            AsposeExprtToExcel.ExportToExcel(ds, templetePath, excelImportTempPath);
            string webAddress = "http://" + this.Request.Url.Authority + this.Request.ApplicationPath;
            webAddress = HttpUtility.UrlEncode(webAddress);
            string url = "/FilesUploadClickOnce/FilesUpload.application?UserId=" + this.CurrentUser.User_ID + "&WebAddress=" + webAddress + "&CatalogId=" + this.ArchiveTypeID + "&Type=Archive" + "&ExcelImportTempPath=" + Uri.EscapeUriString(excelImportTempPath) + "&ApplicationType=ArchiveExport";
            this.Response.Redirect(this.Request.ApplicationPath + url, false);
        }
        /// <summary>
        /// 追加电子文件按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AddFiles_Click(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 删除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Deleted_Click(object sender, EventArgs e)
        {
        }
        #endregion
    }
}